package com.android.server.mock.memory;

import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.ActivityManager;
import android.os.Binder;
import android.os.mock.MockManager;
import android.os.mock.memory.MockMemoryInfo;
import android.util.Log;


import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MockMemoryImpl {
    private static String TAG = MockMemoryImpl.class.getSimpleName();

    private static MockMemoryImpl sMockMemory;

    private MockMemoryInfo mockMemoryInfo;


    private MockMemoryImpl() {
        initialize();
    }

    private static void initialize() {
        //TODO
    }

    public static MockMemoryImpl getInstance() {
        synchronized (MockMemoryImpl.class) {
            if (sMockMemory == null) {
                sMockMemory = new MockMemoryImpl();
            }
            return sMockMemory;
        }
    }

    public boolean parseMemoryInfo(JSONObject deviceInfo) {
        boolean result = false;

        try {
            if (deviceInfo.has("memory")) {
                JSONObject memoryObj = deviceInfo.getJSONObject("memory");
                if(memoryObj != null) {

                    mockMemoryInfo = new MockMemoryInfo();

                    mockMemoryInfo.availMem = memoryObj.getLong("availMem");
                    mockMemoryInfo.lowMemory = memoryObj.getBoolean("lowMemory");
                    mockMemoryInfo.threshold = memoryObj.getLong("threshold");
                    mockMemoryInfo.total = memoryObj.getLong("total");
                    mockMemoryInfo.totalMem = memoryObj.getLong("totalMem");
                    mockMemoryInfo.heapSize = memoryObj.getString("heapSize");
                    mockMemoryInfo.heapGrowthLimit = memoryObj.getString("heapGrowthLimit");
                    mockMemoryInfo.memInfo = memoryObj.getString("memInfo");

                    //TODO: parse meminfo to file for kernel (proc/meminfo)

                    result = true;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "parseMemoryInfo: ", e);
        }

        return result;
    }

    public void getMemoryInfo(ActivityManager.MemoryInfo memoryInfo) {
        if(mockMemoryInfo != null) {
            memoryInfo.totalMem = mockMemoryInfo.totalMem;
            memoryInfo.availMem = mockMemoryInfo.availMem;
            memoryInfo.lowMemory = mockMemoryInfo.lowMemory;
            memoryInfo.threshold = mockMemoryInfo.threshold;
        }
    }

    public MockMemoryInfo getMockMemoryInfo() {
        return mockMemoryInfo;
    }

    public void resetMockMemoryInfo() {
        mockMemoryInfo = null;
        //todo
    }
    
    public boolean needMock() {
        return MockManager.getInstance().isPs(Binder.getCallingUid());
    }
}
